% inputs: x,y are fractional positions on the monitor (0,1)
% stimsize is the size of the ellipsoid in solid angle (radians)
% monitorparams holds the relevant parameters for the monitor and its
% position relative to the mouse's eye

function [stimMask_full,stimMask_roi] = makeVisStimAngularMask_v2_0(x,y,stimsize,monitorparams)

if nargin < 4 || isempty(monitorparams)
    monitorparams.imsz = [1024, 1280];         %in pixels
    monitorparams.screenHeight = 270;          %in mm
    monitorparams.screenWidth = 338;           %in mm
    monitorparams.pixelsize = monitorparams.screenHeight/monitorparams.imsz(1);
    monitorparams.screenDistance = 150;        %in mm
    monitorparams.screenAngle = deg2rad(30); 
    monitorparams.origin = [.35,.5];    %the point on the screen normal to the eye in fraction of the screen coordinates for azimuth and elevation respectively
    [monitorparams.azim,monitorparams.elev] =  pixel2angle_v2_1(monitorparams);
end

origAng = [monitorparams.azim(round(size(monitorparams.azim,1)*y),round(size(monitorparams.azim,2)*x)),...
    monitorparams.elev(round(size(monitorparams.elev,1)*y),round(size(monitorparams.elev,2)*x))];

D = sqrt((monitorparams.azim-origAng(1)).^2 + (monitorparams.elev-origAng(2)).^2);
stimMask = zeros(size(D));
stimMask(D<(stimsize/2)) = 1;
stimMask_full = logical(stimMask);

%can downsample to save memory; if set to 1 then there's no resizing
resize = 1;

%% keep just the part with the ellipse and its position to save memory
a = max(stimMask,[],1);
b = max(stimMask,[],2);
ind = [find(a,1),find(a,1,'last'),find(b,1),find(b,1,'last')];
subim = stimMask(ind(3):ind(4),ind(1):ind(2));
if resize ~= 1
    subim = imresize(subim,resize);
end

% in fractional screen coordinates:
% centerPos = [(mean(ind(1:2)))/monitorparams.imsz(2),...
%     (mean(ind(3:4)))/monitorparams.imsz(1)];
% in pixels
centerPos = [round(mean(ind(1:2))),...
    round(mean(ind(3:4)))];             %this is [x,y]

stimMask_roi.stim = subim;
stimMask_roi.centerPos = centerPos;
stimMask_roi.magnification = 1/resize;

